package cn.jasonone.hm.netdisc.controller;

import cn.jasonone.hm.netdisc.model.pojo.DiskInfo;
import cn.jasonone.hm.netdisc.service.DiskInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Jason
 * @date 2020-07-29 14:56:24
 */
@RestController
@RequestMapping("/download")
public class DownloadController {
	@Resource
	private DiskInfoService diskInfoService;
	
	@Value("${fileupload.root-path}")
	private String rootPath;
	
	@RequestMapping
	public void download(@RequestParam Integer[] ids, HttpServletResponse resp) throws IOException {
		List<DiskInfo> files = diskInfoService.findAllById(ids);
		Map<String, DiskInfo> fileMaps = getFile(files);
		
		Path root = Paths.get(rootPath);
		if(fileMaps.size() == 1){
			List<Map.Entry<String, DiskInfo>> collect = fileMaps.entrySet().stream().collect(Collectors.toList());
			Map.Entry<String, DiskInfo> entry = collect.get(0);
			DiskInfo file = entry.getValue();
			resp.setHeader("Content-Disposition", "attachment;filename="+file.getName());
		}else{
			resp.setContentType("application/zip");
			ZipOutputStream zop=new ZipOutputStream(resp.getOutputStream());
			for (Map.Entry<String, DiskInfo> entry : fileMaps.entrySet()) {
				DiskInfo file = entry.getValue();
				zop.putNextEntry(new ZipEntry(entry.getKey()));
				//  控制指定时间段内写出的字节数
				//  每秒写出256kb
				Files.copy(root.resolve(file.getPath()),zop);
				zop.closeEntry();
				zop.flush();
			}
			zop.close();
		}
	}
	
	private Map<String,DiskInfo> getFile(List<DiskInfo> files){
		Map<String,DiskInfo> map=new HashMap<>();
		for (DiskInfo file : files) {
			if(file.getDirectory() == false){
				map.put(file.getName(),file);
			}else{
				map.putAll(getFile(file.getName(), file));
			}
		}
		return map;
	}
	
	private Map<String,DiskInfo> getFile(String parent,DiskInfo diskInfo){
		Map<String,DiskInfo> map=new HashMap<>();
		if(diskInfo.getFiles() != null && diskInfo.getFiles().size()>0){
			for (DiskInfo file : diskInfo.getFiles()) {
				if(file.getDirectory() == false){
					map.put(parent+File.separator+file.getName(),file);
				}else{
					map.putAll(getFile(parent+File.separator+file.getName(), file));
				}
			}
		}
		return map;
	}
}
